package org.hy.controller.group;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.hy.domain.User;
import org.hy.domain.group.Group;
import org.hy.service.group.IGroupService;
import org.hy.util.AppConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 小组控制器
 * @author xwm
 *
 */
@Controller
@RequestMapping("/group/")
public class GroupController {

	@Autowired
	private IGroupService groupService;
	
	@RequestMapping("list/{page}")
	public String list(@PathVariable("page") int page,Model model) {
		List<Group> groupList = groupService.listRecentGroup(page, AppConstant.PAGE_SIZE);
		int count = 1;
		model.addAttribute("groupList", groupList);
		model.addAttribute("count", count);
		return "group/list";
	}
	
	@RequestMapping("list")
	public String listPage1(Model model) {
		return list(1,model);
	}
	
	@RequestMapping("new")
	public String add(Map<String,Object> model) {
		model.put("edit", false);
		model.put("title", "新增小组");
		model.put("action", "group/create");
		model.put("group", new Group());
		return "group/form";
	}
	
	@RequestMapping("edit/{gid}")
	public String edit(@PathVariable int gid,Map<String,Object> model) {
		Group group = groupService.findGroupById(gid);
		model.put("group", group);
		model.put("edit", true);
		model.put("title", "编辑小组");
		model.put("action", "group/update/"+group.getId());
		return "group/form";
	}
	
	/**
	 * 添加小组
	 * @return
	 */
	@RequestMapping("create")
	public String create( Group group,HttpSession session) {
		group.setIntime(AppConstant.now());
		User loginedUser = (User)session.getAttribute("user");
		group.setFounder(loginedUser);
		groupService.addGroup(group);
		return "redirect:list";
	}
	
	/**
	 * 更新小组
	 * @return
	 */
	@RequestMapping("update/{id}")
	public String update(@PathVariable int id,Group newGroup) {
		Group oldGroup = groupService.findGroupById(id);
		oldGroup.setName(newGroup.getName());
		oldGroup.setDescription(newGroup.getDescription());
		groupService.updateGroup(oldGroup);
		return "redirect:/group/list";
	}
	
	@RequestMapping("delete/{id}")
	public String delete(int id) {
		groupService.deleteGroup(id);
		return "redirect:group/list";
	}
}
